package org.common.eureka.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * 订阅与发布配置
 *
 * @author samphin
 */
@Configuration
public class TopicRabbitConfig {

    public final static String ORDER_INFO_ROUTE_KEY = "topic.order.info";

    public final static String ORDER_INFO_QUEUE_NAME = "order_info_queue";

    public final static String ORDER_INFO_EXCHANGE = "order_info_exchange";

    @Bean
    public Queue orderConsumerQueue() {
        return new Queue(ORDER_INFO_QUEUE_NAME);
    }

    @Bean
    public TopicExchange orderExchange() {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-max-length", 1000);
        arguments.put("content-type","text");
        TopicExchange exchange =
                new TopicExchange(
                        ORDER_INFO_EXCHANGE, true, false, arguments);
        return exchange;
    }

    @Bean
    public Binding bindingExchangeMessage() {
        return BindingBuilder.
                bind(orderConsumerQueue()).
                to(orderExchange()).
                with(ORDER_INFO_ROUTE_KEY);
    }

    //===============生产者发送确认==========
    @Bean
    public RabbitTemplate.ConfirmCallback confirmCallback() {
        return new RabbitTemplate.ConfirmCallback() {

            @Override
            public void confirm(CorrelationData correlationData,
                                boolean ack,
                                String cause) {
                if (ack) {
                    System.out.println("发送者确认发送给mq成功");
                } else {
                    //处理失败的消息
                    System.out.println("发送者发送给mq失败,考虑重发:" + cause);
                }
            }
        };
    }

    @Bean
    public RabbitTemplate.ReturnCallback returnCallback() {
        return new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message,
                                        int replyCode,
                                        String replyText,
                                        String exchange,
                                        String routingKey) {
                System.out.println("无法路由的消息，需要考虑另外处理。");
                System.out.println("Returned replyText：" + replyText);
                System.out.println("Returned exchange：" + exchange);
                System.out.println("Returned routingKey：" + routingKey);
                String msgJson = new String(message.getBody());
                System.out.println("Returned Message：" + msgJson);
            }
        };
    }
}
